import json
import re
import os
import pickle
def read_volume_multiple_from_file(filename):
    """
    从JSON文件读取VolumeMultiple并生成字典
    
    Args:
        filename: JSON文件名
        
    Returns:
        dict: 格式为 {交易所_品种00: VolumeMultiple}
    """
    # 检查文件是否存在
    if not os.path.exists(filename):
        print(f"错误：文件 {filename} 不存在")
        return {}
    
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        volume_dict = {}
        
        for key, value in data.items():
            exchange = value["ExchangeID"]
            instrument = value["InstrumentID"]
            
            # 去掉所有数字并替换成00
            instrument_clean = re.sub(r'\d+', '00', instrument)
            
            new_key = f"{exchange}_{instrument_clean}"
            volume_dict[new_key] = value["VolumeMultiple"]
        
        return volume_dict
    
    except Exception as e:
        print(f"读取文件时出错：{e}")
        return {}

def read_margin_ratio_from_file(margin_filename, volume_dict):
    """
    从保证金文件中读取多头保证金率，使用volume_dict中的市场信息
    
    Args:
        margin_filename: 保证金JSON文件名
        volume_dict: 从第一个函数得到的字典 {市场_品种00: VolumeMultiple}
        
    Returns:
        dict: 格式为 {市场_品种00: LongMarginRatioByMoney}
    """
    if not os.path.exists(margin_filename):
        print(f"错误：文件 {margin_filename} 不存在")
        return {}
    
    try:
        with open(margin_filename, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        margin_dict = {}
        
        print("处理保证金率过程:")
        print("-" * 40)
        
        for key, value in data.items():
            instrument = value["InstrumentID"]
            margin_ratio = value["LongMarginRatioByMoney"]
            
            # 去掉所有数字并替换成00，得到品种代码
            instrument_clean = re.sub(r'\d+', '00', instrument)
            
            # 在volume_dict中查找匹配的市场
            found_market = None
            for volume_key in volume_dict.keys():
                # volume_key的格式是 "市场_品种00"
                market, product = volume_key.split('_')
                if product == instrument_clean:
                    found_market = market
                    break
            
            if found_market:
                new_key = f"{found_market}_{instrument_clean}"
                margin_dict[new_key] = margin_ratio
                print(f"找到匹配: {instrument} -> {new_key} = {margin_ratio}")
            else:
                print(f"警告: 未找到品种 {instrument} 对应的市场信息")
        
        print("-" * 40)
        return margin_dict
    
    except Exception as e:
        print(f"读取保证金文件时出错：{e}")
        return {}
if __name__ == "__main__":
    filename = "Instrument.json"  
    volume_data = read_volume_multiple_from_file(filename)

    margin_data = read_margin_ratio_from_file("MarginRate.json", volume_data)
    print(volume_data)
    print(margin_data)
    with open('volume_multiple.pkl', 'wb') as f:
        pickle.dump(volume_data, f)
    
    with open('margin_ratio.pkl', 'wb') as f:
        pickle.dump(margin_data, f)